package org.jmetrix.bus.impl;

import org.jmetrix.bus.Bus;
import org.jmetrix.bus.Listener;

import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author Konstantin Kuzmin
 * @version $Revision$
 * @since 01.10.11
 */
public class BusImpl implements Bus {
    protected static String onEvent = "onEvent";
    private final Map<Class, Collection<Listener>> eventListeners = new LinkedHashMap<Class, Collection<Listener>>();
    private Publisher publisher = new Publisher();
    private Thread publishingThread = new Thread(publisher, BusImpl.class.getName() + "-PublishingThread");
    protected Queue eventQueue = new ConcurrentLinkedQueue();

    public BusImpl() {
        publishingThread.setDaemon(true);
        publishingThread.start();
    }

    @Override
    public void publish(final Object object) {
        eventQueue.add(object);
        publisher.wakeUp();
    }

    private void doPublish(Object object) {
        //TODO protect from modification of eventListeners.entrySet
        for (final Map.Entry<Class, Collection<Listener>> eventClassListeners : eventListeners.entrySet()) {
            if (eventClassListeners.getKey().isAssignableFrom(object.getClass())) {
                final Collection<Listener> listeners = eventClassListeners.getValue();
                for (final Listener listener : listeners) {
                    listener.onEvent(object);
                }
            }
        }
    }

    @Override
    public void addListener(final Listener listener) {
        final Class eventClass = getEventClass(listener);
        synchronized (eventListeners) {
            Collection<Listener> listeners = eventListeners.get(eventClass);
            if (listeners == null) {
                listeners = new LinkedList<Listener>();
                eventListeners.put(eventClass, listeners);
            }
            listeners.add(listener);
        }
    }

    protected static Class getEventClass(final Listener listener) {
        final Method[] methods = listener.getClass().getMethods();
        Method onEventMethod = null;
        for (final Method method : methods) {
            if (method.getName().equals(onEvent) &&
                    method.getParameterTypes().length == 1) {
                onEventMethod = method;
                break;
            }
        }
        if (onEventMethod == null) {
            throw new IllegalStateException("Cannot evaluate event type to handle - " + onEvent + " method was not detected");
        }
        return onEventMethod.getParameterTypes()[0];
    }

    private class Publisher implements Runnable {
        final Object toPublishSignal = new Object();

        public void wakeUp() {
            synchronized (toPublishSignal) {
                toPublishSignal.notifyAll();
            }
        }

        @Override
        public void run() {
            while (true) {
                try {
                    synchronized (toPublishSignal) {
                        toPublishSignal.wait();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Object event = eventQueue.poll();
                while (event != null) {
                    doPublish(event);
                    event = eventQueue.poll();
                }
            }
        }
    }
}
